<?php
class ChannelAction extends Action {
	
	//栏目插入,这里传参方便采集模块方法调用
	public function insert($data){
		$parentId = $_POST['parentId'];
		$data = empty($data)? array(
				id => String::keyGen(),
				parentId  => $parentId,
				name  => $_POST['name'],
				datatime  => time(),
				total  => 0
			) : $data;
		
		$channel = M('channel');
		$channel -> add($data);
		
		//如果父目录不为空则子结点数加1
		if($parentId){
			$channel -> where('id='.$parentId)->setDec('childNodes'); 
		}
	}
	
	//删除栏目级其子栏目和文单数据
	public function delete(){
		$channelId = $_POST['channelId'];
		$idList = new ArrayList();
		$channel = M('channel');
		$idList -> add($channelId);
		$linkID = FALSE;
		
		$this -> getChilds(&$idList,$channelId,$channel);
		
		while($id = $idList -> pop()){
			$article = A('Article');
			$article -> deleteByChanId($id);
			$linkID = $channel -> where('id='.$channelId) -> delete();
		}
		
		if($linkID){
			$this->ajaxReturn(0,"删除成功",$linkID);
		}else{
			$this->ajaxReturn(1,"删除失败",$linkID);
		}
	}
	
	//栏目数据更改，包括栏目移动和名称更改
	public function update(){
		$channeName = $_POST['channeName'];
		$parentId = $_POST['parentId'];
		$data = array();
		$channel = M('channel');
		
		if(!empty($parentId)){
			array_push($data, $parentId);
		}else if(!empty($channeName)){
			array_push($data, $channeName);
		}
		
		$linkID = $channel -> where('id='.$_POST['channelId'])->save($data); 
		
		if($linkID){
			 $this->ajaxReturn(0,"修改成功",$linkID);
		}else{
			 $this->ajaxReturn(1,"修改失败",$linkID);
		}
	}
	
	//根据id查询，但不查询其子结点
	public function selectSingle (){
		$channel = M('channel');
		$data = $channel -> where('id='.$_POST['channelId'])-> select(); 
		
		if($data){
			 $this->ajaxReturn(0,"栏目信息",$data);
		}else{
			 $this->ajaxReturn(1,"栏目信息",$data);
		}
	}
	
	//查询栏目下一级子节点
	public function selectChilds(){
		$channel = M('channel');
		$data = $channel -> where('parentId='.$_POST['channelId'])->order('datatime')-> select(); 
		
		if($data){
			 $this->ajaxReturn(0,"栏目信息",$data);
		}else{
			 $this->ajaxReturn(1,"栏目信息",$data);
		}
	}
	
	//查询根结点
	public function selectRoot(){
		$channel = M('channel');
		$data = $channel -> where('parentId IS NULL')-> order('datatime') -> select(); 
		
		if($data){
			 $this->ajaxReturn(0,"栏目根结点",$data);
		}else{
			 $this->ajaxReturn(1,"栏目根结点",$data);
		}
	}
	
	//查询当前栏目下面所有的子节点,给文章模块调用 
	public function getByIdChilds($channelId){
		$idList = new ArrayList();
		$channel = M('channel');
		$idList -> add($channelId);
		
		$this -> getChilds(&$idList,$channelId,$channel);
		
		return $idList -> toArray();
	}
	
	//得到栏目所有的方法
	private function getChilds($idList,$channelId,$channelMode){
		$list = $channelMode -> where('parentId='.$channelId) -> getField('id'); 
		foreach ( $list as $value ) {
       		$idList -> add($value);
       		$this -> getChilds($idList,$value,$channelMode);
		}
	}
	
}
?>